package com.wei.lawyer.net.presenter;

import android.content.res.Resources;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.BannerBean;
import com.wei.lawyer.model.BaseDataBean;
import com.wei.lawyer.model.BaseResultBean;
import com.wei.lawyer.model.BookBean;
import com.wei.lawyer.model.CaseBean;
import com.wei.lawyer.model.CompanyServiceBean;
import com.wei.lawyer.model.ContractBean;
import com.wei.lawyer.model.ContractSearchBean;
import com.wei.lawyer.model.FieldBean;
import com.wei.lawyer.model.LawyerBean;
import com.wei.lawyer.model.LawyerClassBean;
import com.wei.lawyer.model.LawyerCommentBean;
import com.wei.lawyer.net.ApiService;
import com.wei.lawyer.net.BaseObserver;
import com.wei.lawyer.net.BasePresenter;
import com.wei.lawyer.net.BaseView;
import com.wei.lawyer.net.RetrofitManager;
import com.wei.lawyer.net.contract.ContractDetailView;
import com.wei.lawyer.net.contract.ContractSearchView;
import com.wei.lawyer.net.contract.ContractView;
import com.wei.lawyer.net.contract.HomeView;
import com.wei.lawyer.sql.ContractBeanDao;
import com.wei.lawyer.utils.RxUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：赵若位
 * 时间：2018/12/7 15:26
 * 邮箱：1070138445@qq.com
 * 功能：
 */
public class HomePresenter extends BasePresenter<BaseView>
{

    public HomePresenter(BaseView view, LifecycleProvider provider)
    {
        super(view, provider);
    }

    /**
     * 获取首页Banner数据
     */
    public void getBannerData()
    {
        add(
                RetrofitManager.getManager().getService().getBannerData()
                        .compose(this.<BaseDataBean<List<BannerBean>>>loadTransformer())
                        .compose(RxUtils.<List<BannerBean>>handleBaseData())
                        .subscribeWith(new BaseObserver<List<BannerBean>>(mView)
                        {
                            @Override
                            public void onNext(List<BannerBean> list)
                            {
                                BaseDataBean<List<BannerBean>> data = new BaseDataBean<>();
                                data.setT(list);
                                if (mView != null && mView instanceof HomeView)
                                {
                                    ((HomeView) mView).showBannerData(data);
                                }
                            }
                        })
        );
    }

    /**
     * 获取服务动态数据
     */
    public void getLawyerServiceData()
    {
        add(
                RetrofitManager.getManager().getService().getLawyerServiceData()
                        .compose(this.<BaseResultBean<List<LawyerBean>>>loadTransformer())
                        .compose(RxUtils.<List<LawyerBean>>handleBaseResult())
                        .subscribeWith(new BaseObserver<List<LawyerBean>>(mView)
                        {
                            @Override
                            public void onNext(List<LawyerBean> list)
                            {
                                BaseDataBean<List<LawyerBean>> data = new BaseDataBean<>();
                                data.setT(list);
                                if (mView != null && mView instanceof HomeView)
                                {
                                    ((HomeView) mView).showServiceData(data);
                                }
                            }
                        })
        );
    }

    /**
     * 获取推荐律师列表
     */
    public void getLawyerRecommentData()
    {
        add(
                RetrofitManager.getManager().getService().getLawyerRecommentData()
                        .compose(this.<BaseResultBean<List<LawyerBean>>>loadTransformer())
                        .compose(RxUtils.<List<LawyerBean>>handleBaseResult())
                        .subscribeWith(new BaseObserver<List<LawyerBean>>(mView)
                        {
                            @Override
                            public void onNext(List<LawyerBean> list)
                            {
                                if (mView != null && mView instanceof HomeView)
                                {
                                    ((HomeView) mView).showRecommentData(list);
                                }
                            }
                        })
        );
    }


    /**
     * 获取法律小讲堂
     */
    public void getLawclassData(int page)
    {
        add(
                RetrofitManager.getManager().getService().getLawclassData(page)
                        .compose(this.<BaseResultBean<List<LawyerClassBean>>>loadTransformer())
                        .compose(RxUtils.<List<LawyerClassBean>>handleBaseResult())
                        .subscribeWith(new BaseObserver<List<LawyerClassBean>>(mView)
                        {
                            @Override
                            public void onNext(List<LawyerClassBean> list)
                            {
                                LawyerClassBean data = (list != null && list.size() != 0) ? list.get(0) : null;
                                if (mView != null && mView instanceof HomeView)
                                {
                                    ((HomeView) mView).showLawClassData(data);
                                }
                            }
                        })
        );
    }

    /**
     * 获取案件委托初始化数据
     */
    public void getCaseData()
    {
        add(
                RetrofitManager.getManager().getService().getCaseData()
                        .compose(this.<BaseDataBean<CaseBean>>loadTransformer())
                        .compose(RxUtils.<CaseBean>handleBaseData())
                        .subscribeWith(new BaseObserver<CaseBean>(mView)
                        {
                            @Override
                            public void onNext(CaseBean data)
                            {
                                if (mView != null)
                                {
                                    mView.showData(data);
                                }
                            }
                        })
        );
    }

    /**
     * 获取文书服务初始化数据
     */
    public void getBookData()
    {
        add(
                RetrofitManager.getManager().getService().getBookData()
                        .compose(this.<BaseDataBean<BookBean>>loadTransformer())
                        .compose(RxUtils.<BookBean>handleBaseData())
                        .subscribeWith(new BaseObserver<BookBean>(mView)
                        {
                            @Override
                            public void onNext(BookBean data)
                            {
                                if (mView != null)
                                {
                                    mView.showData(data);
                                }
                            }
                        })
        );
    }


    /**
     * 合同模板分类
     */
    public void getContractClassification()
    {
        add(
                RetrofitManager.getManager().getService().getContractClassification()
                        .compose(this.<BaseDataBean<List<FieldBean>>>loadTransformer())
                        .compose(RxUtils.<List<FieldBean>>handleBaseData())
                        .subscribeWith(new BaseObserver<List<FieldBean>>(mView)
                        {
                            @Override
                            public void onNext(List<FieldBean> list)
                            {
                                if (mView != null && mView instanceof ContractView)
                                {
                                    ((ContractView) mView).showClassification(list);
                                }
                            }
                        })
        );
    }


    /**
     * 获取合同内容列表
     *
     * @param id
     */
    public void getContractList(int id, int page)
    {
        add(
                RetrofitManager.getManager().getService().getContractList(id, page)
                        .compose(this.<BaseResultBean<List<ContractBean>>>loadTransformer())
                        .compose(RxUtils.<List<ContractBean>>handleBaseResult())
                        .subscribeWith(new BaseObserver<List<ContractBean>>(mView)
                        {
                            @Override
                            public void onNext(List<ContractBean> list)
                            {
                                if (mView != null && mView instanceof ContractView)
                                {
                                    ((ContractView) mView).showContractData(list);
                                }
                            }
                        })
        );
    }

    /**
     * 获取合同详情数据
     *
     * @param contractID
     */
    public void getContractDetail(int contractID)
    {
        ApiService api = RetrofitManager.getManager().getService();
        Flowable<ContractBean> contract = api.getContractDetail(contractID)
                .compose(RxUtils.<ContractBean>handleBaseData());
        Flowable<Boolean> collection = api.getContractCollection(contractID)
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.<Boolean>handleBaseResult());
        add(
                Flowable.zip(contract, collection, new BiFunction<ContractBean, Boolean, ContractBean>()
                {
                    @Override
                    public ContractBean apply(ContractBean contract, Boolean collection) throws Exception
                    {
                        contract.setCollection(collection);
                        return contract;
                    }
                })
                        .compose(this.<ContractBean>loadTransformer())
                        .subscribeWith(new BaseObserver<ContractBean>(mView, true)
                        {
                            @Override
                            public void onNext(ContractBean data)
                            {
                                if (mView != null && mView instanceof ContractDetailView)
                                {
                                    ((ContractDetailView) mView).showContractDetail(data);
                                }
                            }
                        })
        );
    }


    /**
     * 合同详情-收藏
     *
     * @param contractID
     */
    public void collection(int contractID)
    {
        add(
                RetrofitManager.getManager().getService().collection(contractID, 3)
                        .compose(this.<BaseDataBean<Object>>loadTransformer())
                        .compose(RxUtils.handleBaseData())
                        .subscribeWith(new BaseObserver<Object>(mView)
                        {
                            @Override
                            public void onNext(Object o)
                            {
                                if (mView != null && mView instanceof ContractDetailView)
                                {
                                    ((ContractDetailView) mView).showCollection();
                                }
                            }
                        })
        );
    }


    /**
     * 合同详情-取消收藏
     *
     * @param contractID
     */
    public void unCollection(int contractID)
    {
        add(
                RetrofitManager.getManager().getService().unCollection(contractID)
                        .compose(this.<BaseDataBean<Object>>loadTransformer())
                        .compose(RxUtils.handleBaseData())
                        .subscribeWith(new BaseObserver<Object>(mView)
                        {
                            @Override
                            public void onNext(Object o)
                            {
                                if (mView != null && mView instanceof ContractDetailView)
                                {
                                    ((ContractDetailView) mView).showUnCollection();
                                }
                            }
                        })
        );
    }


    /**
     * 从本地查询搜索历史纪录
     *
     * @return
     */
    private Flowable<List<ContractBean>> getContractHistory()
    {
        return Flowable.create(new FlowableOnSubscribe<List<ContractBean>>()
        {
            @Override
            public void subscribe(FlowableEmitter<List<ContractBean>> e) throws Exception
            {
                ContractBeanDao dao = App.mSession.getContractBeanDao();
                /*搜索本地数据并按照搜索时间降序排列*/
                List<ContractBean> list = dao.queryBuilder().orderDesc(ContractBeanDao.Properties.CreateTime).list();
                if (list != null)
                {
                    e.onNext(list);
                }
                e.onComplete();
            }
        }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io());
    }

    /**
     * 获取推荐合同列表
     */
    public void getRecommentContract()
    {
        Flowable<List<ContractBean>> recomment = RetrofitManager.getManager().getService().getRecommentContractData()
                .compose(RxUtils.<List<ContractBean>>handleBaseData())
                .subscribeOn(Schedulers.io());
        add(
                Flowable.zip(recomment, getContractHistory(), new BiFunction<List<ContractBean>, List<ContractBean>, List<ContractSearchBean>>()
                {
                    @Override
                    public List<ContractSearchBean> apply(List<ContractBean> list, List<ContractBean> list2) throws Exception
                    {
                        List<ContractSearchBean> data = new ArrayList<>();
                        Resources resources = App.getContext().getResources();
                        data.add(new ContractSearchBean(resources.getString(R.string.tv_hot_contract), list));
                        data.add(new ContractSearchBean(resources.getString(R.string.tv_contract_now_search), list2));
                        return data;
                    }
                }).compose(this.<List<ContractSearchBean>>loadTransformer())
                        .subscribeWith(new BaseObserver<List<ContractSearchBean>>(mView)
                        {
                            @Override
                            public void onNext(List<ContractSearchBean> list)
                            {
                                if (mView != null && mView instanceof ContractSearchView)
                                {
                                    ((ContractSearchView) mView).showRecommentContract(list);
                                }
                            }
                        })
        );
    }

    /**
     * 获取合同搜索界面的历史搜索记录
     */
    public void getContractHistoryData()
    {
        add(
                getContractHistory()
                        .compose(RxUtils.<List<ContractBean>>rxFlowableSchedulers())
                        .subscribeWith(new BaseObserver<List<ContractBean>>(mView)
                        {
                            @Override
                            public void onNext(List<ContractBean> list)
                            {
                                if (mView != null && mView instanceof ContractSearchView)
                                {
                                    ((ContractSearchView) mView).showHistoryContract(list);
                                }
                            }
                        })
        );
    }


    /**
     * 从服务器查询合同
     *
     * @param descript
     */
    public void getContractSearchData(String descript)
    {
        add(
                RetrofitManager.getManager().getService().getContractSearch(descript)
                        .compose(this.<BaseResultBean<List<ContractBean>>>loadTransformer())
                        .compose(RxUtils.<List<ContractBean>>handleBaseResult())
                        .subscribeWith(new BaseObserver<List<ContractBean>>(mView)
                        {
                            @Override
                            public void onNext(List<ContractBean> list)
                            {
                                if (mView != null && mView instanceof ContractSearchView)
                                {
                                    ((ContractSearchView) mView).showSearchContract(list);
                                }
                            }
                        })
        );
    }


    /**
     * 获取企业服务列表数据
     */
    public void getCompanyData()
    {
        ApiService api = RetrofitManager.getManager().getService();
        Flowable<List<CompanyServiceBean>> service = api.getCompanyServiceData()
                .compose(RxUtils.<List<CompanyServiceBean>>handleBaseResult());
        Flowable<List<CompanyServiceBean>> training = api.getCompanyTrainingData()
                .compose(RxUtils.<List<CompanyServiceBean>>handleBaseResult());
        add(
                Flowable.zip(service, training, new BiFunction<List<CompanyServiceBean>, List<CompanyServiceBean>, List<BaseDataBean<List<CompanyServiceBean>>>>()
                {
                    @Override
                    public List<BaseDataBean<List<CompanyServiceBean>>> apply(List<CompanyServiceBean> list1, List<CompanyServiceBean> list2) throws Exception
                    {
                        Resources resources = App.getContext().getResources();
                        List<BaseDataBean<List<CompanyServiceBean>>> data = new ArrayList<>();
                        data.add(new BaseDataBean<List<CompanyServiceBean>>(resources.getString(R.string.tv_company_service), list1));
                        data.add(new BaseDataBean<List<CompanyServiceBean>>(resources.getString(R.string.tv_company_training), list2));
                        return data;
                    }
                })
                        .compose(this.<List<BaseDataBean<List<CompanyServiceBean>>>>loadTransformer())
                        .subscribeWith(new BaseObserver<List<BaseDataBean<List<CompanyServiceBean>>>>(mView, true)
                        {
                            @Override
                            public void onNext(List<BaseDataBean<List<CompanyServiceBean>>> list)
                            {
                                if (mView != null)
                                {
                                    mView.showData(list);
                                }
                            }
                        })
        );
    }


    /**
     * 获取企业服务详情
     *
     * @param data
     */
    public void getCompanyDetailData(@NonNull final CompanyServiceBean data)
    {
        ApiService api = RetrofitManager.getManager().getService();
        Flowable<CompanyServiceBean> detail = api.getCompanyDetailData(data.getID())
                .compose(RxUtils.<CompanyServiceBean>handleBaseData());
        final Flowable<List<LawyerCommentBean>> comment = api.getCompanyCommentData(data.getID())
                .compose(RxUtils.<List<LawyerCommentBean>>handleBaseResult());
        Flowable.zip(detail, comment, new BiFunction<CompanyServiceBean, List<LawyerCommentBean>, CompanyServiceBean>()
        {
            @Override
            public CompanyServiceBean apply(CompanyServiceBean company, List<LawyerCommentBean> list) throws Exception
            {
                company.setService(data.getService());
                company.setComments(list);
                company.setServiceData();
                return company;
            }
        }).compose(this.<CompanyServiceBean>loadTransformer())
                .subscribeWith(new BaseObserver<CompanyServiceBean>(mView, true)
                {
                    @Override
                    public void onNext(CompanyServiceBean company)
                    {
                        if (mView != null)
                        {
                            mView.showData(company);
                        }
                    }
                });
    }


}
